package com.liyuxiang.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liyuxiang.yygh.common.helper.HttpRequestHelper;
import com.liyuxiang.yygh.enums.OrderStatusEnum;
import com.liyuxiang.yygh.enums.PaymentStatusEnum;
import com.liyuxiang.yygh.enums.PaymentTypeEnum;
import com.liyuxiang.yygh.hosp.client.HospitalFeignClient;
import com.liyuxiang.yygh.model.order.OrderInfo;
import com.liyuxiang.yygh.model.order.PaymentInfo;
import com.liyuxiang.yygh.order.mapper.PaymentMapper;
import com.liyuxiang.yygh.order.service.OrderService;
import com.liyuxiang.yygh.order.service.PaymentService;
import com.liyuxiang.yygh.vo.order.SignInfoVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, PaymentInfo> implements PaymentService {
    @Autowired
    OrderService orderService;
    @Autowired
    HospitalFeignClient hospitalFeignClient;

    @Override
    public void savePaymentInfo(OrderInfo order, Integer paymentType) {
        //根据订单id和支付类型 ，查询支付记录表是否存在
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderId, order.getId());
        queryWrapper.eq(PaymentInfo::getPaymentType, paymentType);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            return;
        }
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderId(order.getId());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setUpdateTime(new Date());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setTotalAmount(BigDecimal.valueOf(0.01));
        paymentInfo.setOutTradeNo(order.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        String subject = new DateTime(order.getReserveDate()).toString("yyyy-MM-dd") + "|" + order.getHosname() + "|" + order.getDepname() + "|" + order.getTitle();
        paymentInfo.setSubject(subject);
        baseMapper.insert(paymentInfo);
    }


    @Override
    public void paySuccess(Map<String, String> parameterMap) {
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOutTradeNo, parameterMap.get("out_trade_no"));
        queryWrapper.eq(PaymentInfo::getPaymentType, PaymentTypeEnum.ALIPAY.getStatus());
        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);
        if (!ObjectUtils.isEmpty(paymentInfo)) {
            //更新支付信息
            paymentInfo.setUpdateTime(new Date());
            paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
            paymentInfo.setTradeNo(parameterMap.get("trade_no").toString());
            paymentInfo.setCallbackTime(new Date());
            paymentInfo.setCallbackContent(parameterMap.toString());
            baseMapper.updateById(paymentInfo);
            //更新订单信息
            OrderInfo orderInfo = orderService.getById(paymentInfo.getOrderId());
            if (!ObjectUtils.isEmpty(orderInfo)) {
                //更新订单信息
                orderInfo.setUpdateTime(new Date());
                orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
                orderService.updateById(orderInfo);
                //调用医院接口，通知已支付
                SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
                if (!ObjectUtils.isEmpty(signInfoVo)) {
                    Map<String, Object> reqMap = new HashMap<>();
                    reqMap.put("hoscode", orderInfo.getHoscode());
                    reqMap.put("hosRecordId", orderInfo.getHosRecordId());
                    reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
                    String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
                    reqMap.put("sign", sign);
                    JSONObject result = HttpRequestHelper.sendRequest(reqMap, "http://localhost:9998/order/updatePayStatus");
                }
            }
        }
    }

    @Override
    public PaymentInfo getPaymentInfo(Long orderId, Integer paymentType) {
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderId, orderId);
        queryWrapper.eq(PaymentInfo::getPaymentType, paymentType);
        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);
        return paymentInfo;
    }
}
